import type { ComponentProps } from "react";
import { useState } from "react";
import { Eye, EyeOff, Lock } from "lucide-react";
import { cn } from "@/lib/utils";

interface PasswordInputProps extends ComponentProps<"input"> {
  startIcon?: React.ReactNode;
  showToggle?: boolean;
}

const PasswordInput = ({
  startIcon,
  showToggle = true,
  className,
  ...inputProps
}: PasswordInputProps) => {
  const [showPassword, setShowPassword] = useState(false);

  const defaultStartIcon = <Lock className="h-4 w-4" />;

  return (
    <div className={cn(
      "h-9",
      "flex items-center w-full min-w-0 rounded-md border bg-transparent shadow-xs transition-[color,box-shadow] outline-none",
      "border-input",
      "focus-within:border-ring",
      "focus-within:ring-1 focus-within:ring-ring/50",
      "aria-invalid:border-destructive aria-invalid:ring-destructive/20",
      "dark:aria-invalid:ring-destructive/40",
      "disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50",
      className,
    )}>
      <div className="flex shrink-0 items-center text-muted-foreground pl-3">
        {startIcon || defaultStartIcon}
      </div>
      <input
        type={showPassword ? "text" : "password"}
        className={cn(
          "flex-1 border-0 bg-transparent outline-none",
          "placeholder:text-muted-foreground/70 placeholder:text-sm",
          "disabled:cursor-not-allowed disabled:opacity-50 h-full w-full",
          "px-3"
        )}
        {...inputProps}
      />
      {showToggle && (
        <div
          className="flex shrink-0 items-center justify-center text-muted-foreground hover:text-foreground h-8 w-8 p-0 mr-1 cursor-pointer"
          onClick={() => setShowPassword(!showPassword)}
        >
          {showPassword ? (
            <EyeOff className="h-4 w-4" />
          ) : (
            <Eye className="h-4 w-4" />
          )}
        </div>
      )}
    </div>
  );
};

export default PasswordInput;
